<template>
    <div class="container">
        <div id="CesiumMapId"></div>
        <div class="top_box">
            <el-select 
            v-model="maptileChange" 
            @change="mapTileChange" 
            placeholder="请选择">
                <el-option 
                v-for="item in mapTileSourceOptions" 
                :key="item.value" 
                :label="item.label"
                :value="item.value">
                </el-option>
            </el-select>
            <div class="btn" @click="positionTo_1">定位到纽约</div>
            <div class="btn" @click="positionTo_2">定位到上海</div>
            <div class="btn" @click="drawPointToMap">绘制一个点</div>
            <div class="btn" @click="positionToPoint">定位到这个点</div>
            <div class="btn" @click="drawLineToMap">绘制一条线</div>
            <div class="btn" @click="positionToLine">定位到这条线</div>
            <div class="btn" @click="drawCircleToMap">绘制一个圆</div>
            <div class="btn" @click="drawPolygonToMap">绘制一个多边形</div>
            <div class="btn" @click="drawAirToMap">绘制一个飞机</div>
            <div class="btn" @click="drawTargetToMap">绘制一个目标</div>
        </div>
        <div class="bottom_box">
            <div class="btn1" @click="changePointToMap">修改一个点</div>
            <div class="btn1" @click="changeLineToMap">修改一条线</div>
            <div class="btn1" @click="changePolygonToMap">修改一个多边形</div>
            <div class="btn1" @click="changeAirToMap">修改飞机</div>
        </div>
    </div>
</template>

<script>
import { color } from 'echarts';

export default {
    data() {
        return {
            viewer: null,
            maptileChange: '初始地图',
            mapTileSourceOptions: [
                { label: "初始地图", value: "初始地图" },
                {
                    label: "ArcGIS(内置)",
                    value: "ArcGIS(内置)",
                },
                {
                    label: "OSM(内置)",
                    value: "OSM(内置)",
                },
                {
                    label: "Google地图",
                    value: "Google地图",
                },
                {
                    label: "OSM",
                    value: "OSM",
                },
                {
                    label: "本地地图",
                    value: "本地地图",
                },
            ],
        }
    },
    mounted() {
        console.log(Cesium);
        this.initMap()
        // this.mapTileChange("本地地图");
        // this.viewer.imageryLayers.addImageryProvider("本地地图");
    },
    methods: {
        initMap() {
            let token =
                "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIyZTJiMmYxOC1iYTY2LTRiMWItYTdjMi0yNGU1MGI0YzRmMTAiLCJpZCI6Mjg4MTM5LCJpYXQiOjE3NDMwNDI5NzJ9.H9k1_iTjUvg5sEEhIeOyivv5wYyjykqltv4NyPiArgk";
            Cesium.Ion.defaultAccessToken = token;
            //第一个参数id,第二个参数是配置项
            this.viewer = new Cesium.Viewer('CesiumMapId', {
                animation: false,
                timeline: false,
                fullscreenButton: false,
                vrButton: false,
                geocoder: false,
                homeButton: false,
                sceneModePicker: false,
                baseLayerPicker: false,
                navigationHelpButton: false,
                infoBox: false,
                selectionIndicator: false,
            });
            this.viewer.camera.setView({
                //笛卡尔坐标系
                destination: Cesium.Cartesian3.fromDegrees(104.0654, 30.5775, 3000000)//经度，纬度
            })
        },
        mapTileChange(val) {
            this.viewer.imageryLayers.removeAll();
            let mapProvider;
            switch (val) {
                case "初始地图":
                    mapProvider = Cesium.createWorldImagery();
                    break;
                case "ArcGIS(内置)":
                    mapProvider = new Cesium.ArcGisMapServerImageryProvider({
                        url: "https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer",
                        layers: "0",
                    });
                    break;
                case "OSM(内置)":
                    mapProvider = new Cesium.OpenStreetMapImageryProvider({
                        url: "https://{s}.tile.openstreetmap.org",
                    });
                    break;
                case "Google地图":
                    mapProvider = new Cesium.UrlTemplateImageryProvider({
                        assetId: "googleMapTile",
                        url: "http://mt{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}",
                        subdomains: ["0", "1", "2", "3"],
                        credit: "Google Maps",
                    });
                    break;
                case "OSM":
                    mapProvider = new Cesium.UrlTemplateImageryProvider({
                        url: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
                        subdomains: ["a", "b", "c"],
                        credit: "OpenStreetMap Contributors",
                        minimumLevel: 0,
                        maximumLevel: 19,
                    });
                    break;
                case "本地地图":
                    mapProvider = new Cesium.UrlTemplateImageryProvider({
                        url: "mapTile/{z}/{x}/{y}.png",
                        minimumLevel: 0,
                        maximumLevel: 10,
                    });
                    break;
                default:
                    // 添加默认地图源
                    mapProvider = Cesium.createWorldImagery();
                    break;
            }
            if (!mapProvider) return;
            this.viewer.imageryLayers.addImageryProvider(mapProvider);
        },
    positionTo_1(){
        this.viewer.camera.setView({
            destination:Cesium.Cartesian3.fromDegrees(-74.0006,40.7218,3000000),
        });
    },
    positionTo_2(){
        this.viewer.camera.flyTo({
            destination:Cesium.Cartesian3.fromDegrees(121.4737,31.2304,3000000),
            duration:2,
            maximumHeight:3000000//飞行最高高度
        })
    },
    drawPointToMap(){
        let point = this.viewer.entities.add({
            id:"point_1",
            position:Cesium.Cartesian3.fromDegrees(103.54,30.8,0),
            point:{
                color:Cesium.Color.RED,
                pixelSize:10,
                outlineColor:Cesium.Color.BLACK,
                outlinWidth:2,
                heightReference:Cesium.HeightReference.CLAMP_TO_GROUND,
            }
        })
    },
    positionToPoint(){
        //1.拿到点,获取到点
        let point=this.viewer.entities.getById("point_1");
        //获取到实体的位置信息，但是现在这个是三维笛卡尔坐标
        let position=point.position.getValue();
        console.log(position)
        //转化为Cartographic格式
        let cartographic = Cesium.Cartographic.fromCartesian(position);//Cartographic格式
        //转化为经纬度
        let longitude = Cesium.Math.toDegrees(cartographic.longitude);//经度
        let latitude = Cesium.Math.toDegrees(cartographic.latitude)//纬度
        let height =cartographic.height
        // 获取当前的高度
        let currentCartographic =this.viewer.camera.positionCartographic;
        this.viewer.camera.flyTo({
           destination:Cesium.Cartesian3.fromDegrees(
            longitude,
            latitude,
            currentCartographic.height
            ),
            duration:2,
        })
    },
    drawLineToMap(){
        let coords=[
            [103.54,30.8],
            [103.54,31.8],
            [103.54,30.8],
            [103.54,31.8],
            [107.54,30.9],
            [120.54,30.9],
        ];
        let finalArr =coords.reduce((current,item) =>{
            current.push(...item);
            return current;
        },[]);
        this.viewer.entities.add({
            id:"line_1",
            polyline:{
                positions:Cesium.Cartesian3.fromDegreesArray(finalArr),//坐标数组   arr=[x,y,z,w,m,n] [经度，纬度，经度，纬度]
                width:2,//线宽
                material:Cesium.Color.fromCssColorString("rgba(255,255,0,0.8)"),//转换css中能够写的颜色
                clampTonGround:true,//是否贴地
                arcType:Cesium.ArcType.GEODESIC,//线段类型（测地线或直线）
            },
        });
    },
positionToLine(){
            let point =this.viewer.entities.getById("line_1");
            console.log(point);
            let position=point.polyline.positions.getValue()[0]//定位到线的第一个点 ，现在是笛卡尔三维坐标
            console.log("线的",position);
            
            let cartographic = Cesium.Cartographic.fromCartesian(position);//Cartographic格式
            //转化为经纬度
        let longitude = Cesium.Math.toDegrees(cartographic.longitude);//经度
        let latitude = Cesium.Math.toDegrees(cartographic.latitude)//纬度
        let height =cartographic.height
        // 获取当前的高度
        let currentCartographic =this.viewer.camera.positionCartographic;
        this.viewer.camera.flyTo({
           destination:Cesium.Cartesian3.fromDegrees(
            longitude,
            latitude,
            currentCartographic.height
            ),
            duration:2,
        })
    },
drawCircleToMap() {
  this.viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(121.4737, 31.2304, 0),
    name: "上海圆形范围",
    ellipse: {
      semiMajorAxis: 5000, // 半长轴（半径，米）
      semiMinorAxis: 5000, // 半短轴（与半长轴相等时为圆）
      height: 0, // 高度
      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // 贴地
      material: Cesium.Color.fromCssColorString("rgba(255, 255, 0, 0.5)"), // 修正颜色值
      outline: true,
      outlineColor: Cesium.Color.BLACK,
      outlineWidth: 2,
      extrudedHeight: 0,
    }
  });
},
drawPolygonToMap(){
        let lonAndLatArr =[
            [103.54,30.8],
            [104.54,30.8],
            [104.54,31.8],
            [103.54,31.8],
        ];
        let resultArr = lonAndLatArr.reduce((curr,o) =>{
            curr.push(...o);
            return curr;
        },[]);
        this.viewer.entities.add({
            id:"polygn_1",
            polygon:{
                hierarchy:{
                    positions:Cesium.Cartesian3.fromDegreesArray(resultArr),
                },//顶点坐标
                material:Cesium.Color.fromCssColorString("rgba(255,255,255,0.3)"),
                outline:true,
                outlineColor:Cesium.Color.fromCssColorString("rgba(255,255,255,1)"),
                outlinWidth:3
            }
        })
},
drawAirToMap(){
    const entity =this.viewer.entities.add({
        id:"air_1",
        position:Cesium.Cartesian3.fromDegrees(103.54,30.8,0),
        billboard:{
            image:"/assets/feiji.png",
            scale:1.0,//缩放比例
            color:Cesium.Color.fromCssColorString("#ffffff"),
            rotation:Cesium.Math.toRadians(-45),//设置旋转角度
            width:50,//指定宽度（像素）
            height:50//指定高度（像素）

        }
    })
},
changePointToMap(){
    //需要获取点的实体对象
    let entity=this.viewer.entities.getById("point_1");
    if(!entity) return;
    //2.修改点的位置
    entity.position =Cesium.Cartesian3.fromDegrees(105.54,30.8,0);
    //3.修改点的颜色
    entity.point.color =Cesium.Color.WHITE;
    //4.修改点的显隐
    // setTimeout(()=>{
    //     entity.show =false;
    // },3000);
},
changeLineToMap(){
    const entity=this.viewer.entities.getById("line_1");
    if(!entity) return;
    const newCoords = [
            [113.54,30.8],
            [113.54,29.8],
            [118.54,29.8],
            [120.54,29.8],
            [121.54,30.9],
            [121.54,29.8],
  ];
  // 3. 坐标转换
  const finalArr = newCoords.reduce((acc, [lon, lat]) => {
    acc.push(lon, lat);
    return acc;
  }, []);
  const cartesian3Arr = Cesium.Cartesian3.fromDegreesArray(finalArr);
      entity.polyline.positions=cartesian3Arr
},
changePolygonToMap() {
  const entity = this.viewer.entities.getById("polygn_1");
  if (!entity) return;

  // 获取当前顶点数组（转换为原生数组）
  const currentHierarchy = entity.polygon.hierarchy.getValue();
  const currentPositions = currentHierarchy.positions.toArray();

  // 添加新顶点
  const newPoint = Cesium.Cartesian3.fromDegrees(102.54, 31.5);
  const newPositions = [...currentPositions, newPoint];

  // 闭合多边形（确保首尾相同）
  if (newPositions.length > 0) {
    newPositions.push(newPositions[0]);
  }

  // 更新多边形顶点（使用 Cesium.Cartesian3Array）
  entity.polygon.hierarchy = new Cesium.PolygonHierarchy({
    positions: new Cesium.Cartesian3Array.fromArray(newPositions)
  });

  // 定位到新多边形（可选）
  this.viewer.zoomTo(entity);
}
    }
}
</script>

<style lang="scss" scoped>
.container {
    width: 100%;
    height: 100%;

    #CesiumMapId {
        width: 100%;
        height: 100%;
    }

    .top_box {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 50px;
        background-color: #1f1b1b;
        display: flex;
        .btn{
            width: 120px;
            height: 40px;
            margin-left: 10px;
            margin-top: 5px;
            line-height: 40px;
            background-color: antiquewhite;
            border-radius: 5px;
        }
    }
    .bottom_box{
        position: absolute;
       bottom: 0;
        left: 0;
        width: 100%;
        height: 70px;
        background-color: #1f1b1b;
        display: flex;
        .btn1{
            width: 120px;
            height: 40px;
            margin-left: 10px;
            margin-bottom: 5px;
            line-height: 40px;
            background-color: rgb(79, 180, 239);
            border-radius: 5px;
        }
    }
}
</style>